/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class Solution {
    ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(null == headA || null == headB) {
            return null;
        }
        ListNode l1 = headA;
        ListNode l2 = headB;
        while(null != l1 && null != l2) {
            l1 = l1.next;
            l2 = l2.next;
        }
        if(null == l1) {
            l1 = headB;
            while(null != l2) {
                l2 = l2.next;
                l1 = l1.next;
            }
            l2 = headA;
        }
        if(null == l2) {
            l2 = headA;
            while(null != l1) {
                l1 = l1.next;
                l2 = l2.next;
            }
            l1 = headB;
        }
        while(null != l1 && null != l2) {
            if(l1 == l2) {
                return l1;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return null;
    }
}